import { NextRequest, NextResponse } from 'next/server';
import { getDb } from '@/lib/db';

export async function GET(request: NextRequest) {
  try {
    const db = await getDb();
    const { searchParams } = new URL(request.url);
    
    // 解析分页参数
    const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
    const pageSize = Math.min(100, Math.max(1, parseInt(searchParams.get('pageSize') || '20')));
    
    // 解析分类过滤
    const type = searchParams.get('type') || ''; // txt2img | img2img | extra-single-image | ''(全部)
    
    // 解析排序
    const sortBy = searchParams.get('sortBy') || 'createdAt';
    const sortOrder = (searchParams.get('sortOrder') || 'desc') as 'asc' | 'desc';

    // 根据类型确定查询的 collection
    const collections = type ? [getCollectionName(type)] : ['txt2img_records', 'img2img_records', 'extras_records'];
    
    let allRecords: any[] = [];
    let totalCount = 0;

    // 查询各个 collection
    for (const collection of collections) {
      try {
        const records = await db.findMany(collection, {}, { 
          page: 1, 
          pageSize: 10000, // 先取大量数据用于排序
          sortBy, 
          sortOrder 
        });
        
        if (records.success && records.data) {
          // 为每条记录添加类型标识
          const recordsWithType = records.data.map(record => ({
            ...record,
            recordType: getTypeFromCollection(collection)
          }));
          allRecords.push(...recordsWithType);
        }

        // 计算总数
        const countResult = await db.count(collection, {});
        if (countResult.success) {
          totalCount += countResult.data || 0;
        }
      } catch (err) {
        console.warn(`查询 ${collection} 失败:`, err);
      }
    }

    // 统一排序
    allRecords.sort((a, b) => {
      const aVal = a[sortBy] || a.createdAt || '';
      const bVal = b[sortBy] || b.createdAt || '';
      
      if (sortOrder === 'asc') {
        return aVal > bVal ? 1 : -1;
      } else {
        return aVal < bVal ? 1 : -1;
      }
    });

    // 手动分页
    const startIndex = (page - 1) * pageSize;
    const paginatedRecords = allRecords.slice(startIndex, startIndex + pageSize);

    return NextResponse.json({
      success: true,
      data: paginatedRecords,
      pagination: {
        page,
        pageSize,
        total: allRecords.length,
        totalPages: Math.ceil(allRecords.length / pageSize)
      }
    });

  } catch (error: any) {
    console.error('查询创作记录失败:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Internal Server Error', 
        detail: error.message 
      },
      { status: 500 }
    );
  }
}

// 根据类型获取 collection 名称
function getCollectionName(type: string): string {
  switch (type) {
    case 'txt2img':
      return 'txt2img_records';
    case 'img2img':
      return 'img2img_records';
    case 'extra-single-image':
      return 'extras_records';
    default:
      return 'txt2img_records'; // 默认
  }
}

// 根据 collection 名称获取类型
function getTypeFromCollection(collection: string): string {
  switch (collection) {
    case 'txt2img_records':
      return 'txt2img';
    case 'img2img_records':
      return 'img2img';
    case 'extras_records':
      return 'extra-single-image';
    default:
      return 'unknown';
  }
}